package com.example.loginsystem.api;

import com.example.loginsystem.bean.MyUser;
import com.example.loginsystem.bean.Role;
import com.example.loginsystem.model.Paging;
import com.example.loginsystem.model.Result;
import com.example.loginsystem.service.MyUserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Cheung0
 * Created on 2021/11/12
 */
@RestController
@RequestMapping("/api/user")
public class MyUserAPI {

    @Autowired
    private MyUserService myUserService;

    @PostMapping("/add")
    private Result<MyUser> save(@RequestParam String userName, @RequestParam String password, @RequestParam int roleId) {
        MyUser myUser = new MyUser();
        myUser.setUserName(userName);
        myUser.setPassword(password);
        Role role = new Role();
        role.setId(roleId);
        if (roleId == 0) {
            role.setRoleName("ROLE_admin");
        } else {
            role.setRoleName("ROLE_user");
        }
        Set<Role> roles = new HashSet<>();
        roles.add(role);
        myUser.setRoles(roles);
        return myUserService.add(myUser);
    }

    @DeleteMapping("/delete/{id}")
    private Result<MyUser> delete(@PathVariable("id") int id) {
        return myUserService.delete(id);
    }

    @PostMapping("/update")
    private Result<MyUser> update(@RequestParam String userName, @RequestParam String password, @RequestParam int roleId) {
        MyUser myUser = new MyUser();
        myUser.setUserName(userName);
        myUser.setPassword(password);
        Role role = new Role();
        role.setId(roleId);
        if (roleId == 0) {
            role.setRoleName("ROLE_admin");
        } else {
            role.setRoleName("ROLE_user");
        }
        Set<Role> roles = new HashSet<>();
        roles.add(role);
        myUser.setRoles(roles);
        return myUserService.update(myUser);
    }

    @GetMapping("/getUserByPage/{page}/{size}")
    public Paging<MyUser> getPageInfo(@PathVariable("page") int currentPage, @PathVariable("size") int pageSize) {
        Paging<MyUser> list = myUserService.getByPage(currentPage, pageSize);
        return list;
    }

    @GetMapping("/getByUserName/{userName}")
    public Result<MyUser> getByUserName(@PathVariable("userName") String userName) {
        return myUserService.getByUserName(userName);
    }

    @GetMapping("/getAll")
    private Result<List<MyUser>> getAll() {
        List<MyUser> myUserList;
        myUserList = myUserService.getAll();
        Result result = new Result();
        result.setResultSuccess("查询所有用户成功！", myUserList);
        return result;
    }

}
